package use.io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 序列化就是将一个对象转换成字节序列，方便存储和传输。
 * 序列化：ObjectOutputStream.writeObject()
 * 反序列化：ObjectInputStream.readObject()
 * 不会对静态变量进行序列化，因为序列化只是保存对象的状态，静态变量属于类的状态。
 */
public class ObjectOperation {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        List<A> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            A a1 = new A(i, "abc");
            list.add(a1);
        }
        String objectFile = "/tmp/a1";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(objectFile));
        oos.writeObject(list);
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(objectFile));
        List<A> a2 = (List) ois.readObject();
        ois.close();
        System.out.println(a2);
        for (A a : a2) {
            System.out.println(a);
        }
    }

    private static class A implements Serializable {
        private int x;
        private String y;

        A(int x, String y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "x=" + x + " " + "y=" + y;
        }
    }
}
